package controller

import (
	"danmu/common"
	"danmu/model"
	"danmu/response"
	"danmu/util"
	"github.com/gin-gonic/gin"
	"net/http"
)

//之后改成使用Redis

func SendCode(ctx *gin.Context)  {
	DB :=common.GetDB()
	var requestUser = model.User{}
	var code = model.Code{}
	err := ctx.Bind(&requestUser)
	if err != nil{
		response.Response(ctx,http.StatusBadRequest,400,nil,"请求错误")
		return
	}
	email := requestUser.Email
	randomCode := util.RandomCode(6)
	if !util.VerifyEmailFormat(email) {
		response.Response(ctx,http.StatusUnprocessableEntity,422,nil,"邮箱格式有误")
		return
	}
	DB.Where("email = ?",email).First(&code)
	if code.ID == 0{
		newCode := model.Code{
			Email:email,
			Code:randomCode,
		}
		DB.Create(&newCode)
	}else{
		minute := util.GetMinuteDiffer(code.UpdatedAt)
		if minute < 1{
			response.Fail(ctx,nil,"发送过于频繁")
			return
		} else{
			//更新验证码
			DB.Model(&code).Update("code",randomCode)
		}
	}
	send := util.SendEmail(email,randomCode)
	if send{
		response.Success(ctx,nil,"发送成功")
	}else{
		response.Fail(ctx,nil,"发送失败")
	}
}

func VerificationCode(email string,code string) int {
	DB :=common.GetDB()
	var dbCode = model.Code{}
	DB.Where("email = ? AND code = ?",email,code).First(&dbCode)
	if dbCode.ID == 0{
		//验证码不存在
		return 1
	}else{
		minute := util.GetMinuteDiffer(dbCode.UpdatedAt)
		if minute > 5{
			//验证码失效
			return -1
		}
		return 0
	}
}

